package com.bangdream.michelia.presenter;

import android.app.ProgressDialog;
import android.database.Observable;
import android.util.Log;

import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.CoursesContract;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.CertBean;
import com.bangdream.michelia.entity.CommentBean;
import com.bangdream.michelia.entity.FinishedStateBean;
import com.bangdream.michelia.entity.LearningBean;
import com.bangdream.michelia.entity.LearningStateBean;
import com.bangdream.michelia.entity.courses.CourseInfoBean;
import com.bangdream.michelia.entity.courses.CoursesBean;
import com.bangdream.michelia.entity.CoursesTypeBean;
import com.bangdream.michelia.entity.courses.VideoMsgBean;
import com.bangdream.michelia.model.ICoursesModelImpl;
import com.bangdream.michelia.presenter.base.BasePresenter;
import com.bangdream.michelia.tool.rejava.BaseObserverEntityNormalHttp;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.tool.retrofithttp.TokenManagerDef;
import com.bangdream.michelia.utils.L;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @date on 2018/8/1 20:57
 * @email 909732184@qq.com
 * 课程服务
 */
public class CoursesPresenter<V> extends BasePresenter<V> {
    private static final String TAG = "CoursesPresenter";
    private CoursesContract.ICoursesModel model;

    public CoursesPresenter() {
        model = new ICoursesModelImpl();
    }

    public void getCoursesListData(final int pageNo, int pageSize, final CoursesContract.CoursesType type, ProgressDialog dialog) {
        if (getMyView() == null)
            return;
        setPd(dialog);
        //公开状态（ 0：个人 1.指定人员可见 2：公开）
        getCoursesListData(pageNo, pageSize, type, null, dialog);
    }

    public void getCourseInfo(Map paramsMap, ProgressDialog dialog) {

        final CoursesContract.ICoursesInfo infoView = (CoursesContract.ICoursesInfo) obtainView();
        if (infoView == null)
            return;
        setPd(dialog);

        TokenManagerDef.work(() -> model.getCourseInfo(paramsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<CourseInfoBean>(this, dialog) {
                    @Override
                    public void onHandleSuccess(CourseInfoBean data) {
                        if (infoView == null)
                            return;
                        infoView.setCourseInfo(true, data);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        L.v("okhttp", "错误===" + message);
//                        iView.setCoursestList(false,pageNo,type,null,message);
                    }
                });
    }

    public void getVideoMsg(String id, ProgressDialog dialog) {
        final CoursesContract.ICoursesInfo infoView = (CoursesContract.ICoursesInfo) obtainView();
        if (infoView == null)
            return;
        setPd(dialog);

        TokenManagerDef.work(() -> model.getVideoMsg(id)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<VideoMsgBean>(this, dialog) {
                    @Override
                    public void onHandleSuccess(VideoMsgBean data) {
                        if (infoView == null)
                            return;
//                        infoView.setCourseInfo(true,data);
                        infoView.setVideo(data);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                    }
                });
    }


    /**
     * @param pageNo
     * @param pageSize
     * @param type
     * @param paramsMap 查询条件
     * @param dialog
     */
    public void getCoursesListData(final int pageNo, int pageSize, final CoursesContract.CoursesType type, Map paramsMap, ProgressDialog dialog) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        if (paramsMap == null) {
            paramsMap = new HashMap();
        }
        paramsMap.put("pageNo", pageNo);
        paramsMap.put("pageSize", pageSize);
        //公开状态（ 0：个人 1.指定人员可见 2：公开）
        //paramsMap.put("publicState","2");
        Map finalParamsMap = paramsMap;
        TokenManagerDef.work(() -> model.getCoursesList(finalParamsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<CoursesBean>>(this, dialog) {
                    @Override
                    public void onHandleSuccess(List<CoursesBean> data) {
                        if (iView == null)
                            return;
                        iView.setCoursestList(true, pageNo, type, data, getDescribe(data));
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setCoursestList(false, pageNo, type, null, message);
                    }
                });
    }


    public void getTaskCoursesList(final int pageNo, int pageSize, final CoursesContract.CoursesType type, Map paramsMap, ProgressDialog dialog) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        if (paramsMap == null) {
            paramsMap = new HashMap();
        }
        paramsMap.put("pageNo", pageNo);
        paramsMap.put("pageSize", pageSize);
        //公开状态（ 0：个人 1.指定人员可见 2：公开）
        //paramsMap.put("publicState","2");
        Map finalParamsMap = paramsMap;
        TokenManagerDef.work(() -> model.getTaskCoursesList(finalParamsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<CoursesBean>>(this, dialog) {
                    @Override
                    public void onHandleSuccess(List<CoursesBean> data) {
                        if (iView == null)
                            return;
                        iView.setCoursestList(true, pageNo, type, data, getDescribe(data));
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setCoursestList(false, pageNo, type, null, message);
                    }
                });
    }



    /**
     * @param pageNo
     * @param pageSize
     * @param paramsMap 查询条件
     * @param dialog
     */
    public void getTeacherCoursesListData(final int pageNo, int pageSize, Map paramsMap, ProgressDialog dialog) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        if (paramsMap == null) {
            paramsMap = new HashMap();
        }
        paramsMap.put("pageNo", pageNo);
        paramsMap.put("pageSize", pageSize);
        //公开状态（ 0：个人 1.指定人员可见 2：公开）
        //paramsMap.put("publicState","2");

        Map finalParamsMap = paramsMap;
        TokenManagerDef.work(() -> model.getTeacherCoursesList(finalParamsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<CoursesBean>>(this, dialog) {
                    @Override
                    public void onHandleSuccess(List<CoursesBean> data) {
                        if (iView == null)
                            return;
                        iView.setCoursestList(true, pageNo, CoursesContract.CoursesType.Ordinary, data, getDescribe(data));
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setCoursestList(false, pageNo, CoursesContract.CoursesType.Ordinary, null, message);
                    }
                });
    }

    /**
     * 获取评论列表
     *
     * @param pageNo
     * @param pageSize
     * @param dialog
     */
    public void getCommentListData(final int pageNo, int pageSize, String courseId, ProgressDialog dialog) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        Map paramsMap = new HashMap();
        //paramsMap.put("pageNo",pageNo);
        //paramsMap.put("pageSize",pageSize);
        paramsMap.put("courseId", courseId);
        TokenManagerDef.work(() -> model.getCommentList(paramsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<CommentBean>>(this, dialog) {
                    @Override
                    public void onHandleSuccess(List<CommentBean> data) {
                        if (iView == null)
                            return;
                        iView.setCommentList(true, pageNo, data, getDescribe(data));
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setCommentList(false, pageNo, null, message);
                    }
                });
    }

    /**
     * 评论课程
     *
     * @param dialog
     */
    public void actionComment(String courseId, String content, int star, ProgressDialog dialog) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        Map paramsMap = new HashMap();
        paramsMap.put("courseId", courseId);
        paramsMap.put("userId", AppCurrentUser.getInstance().getUserInfo().getId());
        if (content != null)
            paramsMap.put("content", content);
        paramsMap.put("star", star);
        TokenManagerDef.work(() -> model.actionComment(paramsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<CommentBean>(this, dialog) {
                    @Override
                    public void onHandleSuccess(CommentBean data) {
                        if (iView == null)
                            return;
                        iView.actionComment(true, "评论成功");
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.actionComment(false, message);
                    }
                });
    }

    public void getLearning(int page, int pageNo, int type) {
        final CoursesContract.ICourseLearning iView = (CoursesContract.ICourseLearning) obtainView();
        if (iView == null)
            return;
        Map paramsMap = new HashMap();
        paramsMap.put("pageNo", page);
        paramsMap.put("pageSize", pageNo);
        paramsMap.put("status", type);

        TokenManagerDef.work(() -> model.getLearning(paramsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<LearningBean>>(this, null) {
                    @Override
                    public void onHandleSuccess(List<LearningBean> data) {
                        iView.setLearningList(true, data);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setLearningList(false, null);
                    }
                });
    }


    //获取课程详情
    public void getCoursesDetails(String id) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        TokenManagerDef.work(() -> model.getCoursesDetails(id)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<CoursesBean>(this, pd) {
                    @Override
                    public void onHandleSuccess(CoursesBean coursesBean) {
                        if (iView == null)
                            return;
                        if (coursesBean != null)
                            L.d("课程详情" + coursesBean.toString());
                        iView.setCoursesDetails(true, coursesBean, getDescribe(coursesBean));
                    }
                });
    }

    //获取课程分类列表
    public void getCoursesTypeListData(ProgressDialog dialog) {
        final CoursesContract.ICoursesView iView = getMyView();
        if (iView == null)
            return;
        setPd(dialog);
        TokenManagerDef.work(() -> model.getCoursesTypeList()).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<CoursesTypeBean>>(this, pd) {
                    @Override
                    public void onHandleSuccess(List<CoursesTypeBean> beanList) {
                        try {
                            iView.setCoursesTypeList(true,
                                    tranCoursesTypeList(null, beanList), getDescribe(beanList));
                        } catch (Exception e) {
                            L.e(e.toString());
                            iView.setCoursesTypeList(true, new ArrayList<>(), "");
                        }

                    }
                });
    }


    //课程类型为多级数组 转为一级数组
    private List<CoursesTypeBean> tranCoursesTypeList(List<CoursesTypeBean> beans, List<CoursesTypeBean> beanList) {
        if (beanList == null || beanList.size() < 1)
            return new ArrayList<>();
        if (beans == null) {
            beans = new ArrayList<>();
        }
        for (int i = 0; i < beanList.size(); i++) {
            beans.add(beanList.get(i));
//            tranCoursesTypeList(beans, beanList.get(i).getNodes());
        }
        return beans;
    }

    public void getLearningState() {
        final CoursesContract.ILearningState iView = (CoursesContract.ILearningState) obtainView();
        if (iView == null)
            return;
        TokenManagerDef.work(() -> model.getLearningstate()).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<LearningStateBean>(this, pd) {
                    @Override
                    public void onHandleSuccess(LearningStateBean beanList) {
                        iView.setLearningState(true, beanList);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        super.onHandleError(code, message);
                        iView.setLearningState(false, null);

                    }
                });
    }

    public void getCertList(final int pageNo, int pageSize) {
        final CoursesContract.IMyCertList iView = (CoursesContract.IMyCertList) obtainView();
        if (iView == null)
            return;
        Map paramsMap = new HashMap();
        paramsMap.put("pageNo", pageNo);
        paramsMap.put("pageSize", pageSize);


        TokenManagerDef.work(() -> model.getCertList(paramsMap)).compose(TokenManagerDef.newInstance().getTransformer())
                .compose(composeFunction)
                .subscribe(new BaseObserverEntityNormalHttp<List<CertBean>>(this, pd) {
            @Override
            public void onHandleSuccess(List<CertBean> beanList) {
                iView.setCertList(true, pageNo, beanList);
            }

            @Override
            public void onHandleError(int code, String message) {
                super.onHandleError(code, message);
                iView.setCertList(false, pageNo, null);

            }
        });

    }


    private CoursesContract.ICoursesView getMyView() {
        return (CoursesContract.ICoursesView) obtainView();
    }
}
